package cn.com.ghy.android.widget.coopvisit;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.ghy.android.bean.CoopVisitInfoBean;
import cn.com.ghy.android.bean.CoopVisitOptionInfoBean;
import cn.com.ghy.android.bean.CoopVisitSmallShopInfoBean;
import cn.com.ghy.android.bean.LoginInfoBean;
import cn.com.ghy.android.exception.DisposeException;
import cn.com.ghy.android.service.VsPartOpeService;
import cn.com.ghy.android.util.CommonStatic;
import cn.com.ghy.android.widget.ComStaticApp;
import cn.com.ghy.android.widget.R;

public class CoopVisitSmallShop extends TabActivity {

	private TextView labTxtSmallShopId = null;
	private TextView labTxtSmallShopName = null;
	private TextView labTxtNotSalenum = null;

	private EditText txtContent = null;
	private EditText txtPernr = null;
	private EditText txtCustnum = null;
	private EditText txtSalenum = null;
	private EditText txtCustdisplay = null;
	private EditText txtFirstcmptdisplay = null;

	private CheckBox chkIssale = null;
	private CheckBox chkPjpvisit = null;
	private CheckBox chkPrepare = null;
	private CheckBox chkRegardcust = null;
	private CheckBox chkCleanshelf = null;
	private CheckBox chkSdh = null;
	private CheckBox chkStock = null;
	private CheckBox chkRecorder = null;
	private CheckBox chkThisbuy = null;

	private Spinner spiChannel = null;
	private Spinner spiChoosesku = null;
	private Spinner spiExpress = null;
	private Spinner spiPersu = null;

	private Button labTxtEntertime = null;
	private Button labTxtLeavetime = null;
	private Button btnSubmit01 = null;
	private Button btnSubmit02 = null;
	private Button btnSubmit03 = null;

	private ProgressDialog progressDialog = null;

	private Bundle bundle = null;
	private LoginInfoBean loginInfo = null;
	private CoopVisitInfoBean coopVisitInfo = null;
	private CoopVisitSmallShopInfoBean coopVisitSmallShopInfo = null;
	private List<CoopVisitSmallShopInfoBean> coopVisitSmallShopInfoList = null;
	private List<CoopVisitOptionInfoBean> option = null;
	private ArrayAdapter<CoopVisitOptionInfoBean> spiAdapter = null;
	private List<CoopVisitOptionInfoBean> optionChannle = null;
	private ArrayAdapter<CoopVisitOptionInfoBean> spiChannleAdapter = null;
	private static final String VSTYPE = CommonStatic.VSTYPE_SMALL;

	private HttpThread httpThread = null;

	private DisposeException disposeException = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.coop_visit_small_shop);
		getSession();
		TabHost tabHost = getTabHost();

		TabSpec tab1 = tabHost.newTabSpec("tab1");
		tab1.setIndicator("基本信息");
		tab1.setContent(R.id.linBaseInfo);
		tabHost.addTab(tab1);

		TabSpec tab2 = tabHost.newTabSpec("tab2");
		tab2.setIndicator("前期准备");
		tab2.setContent(R.id.linPlan);
		tabHost.addTab(tab2);

		TabSpec tab3 = tabHost.newTabSpec("tab3");
		tab3.setIndicator("步骤及销售技巧");
		tab3.setContent(R.id.linSetp);
		tabHost.addTab(tab3);

		tabHost.setCurrentTab(0);

		TabWidget tabWidget = tabHost.getTabWidget();
		for (int i = 0; i < tabWidget.getChildCount(); i++) {
			tabWidget.getChildAt(i).getLayoutParams().height = getWindowManager()
					.getDefaultDisplay().getHeight() / 12;
		}

		findView();
		init();
		addListener();
	}

	@SuppressWarnings("unchecked")
	private void getSession() {
		disposeException = ((ComStaticApp) getApplication()).getDisposeException();
		loginInfo = ((ComStaticApp) getApplication()).getLoginInfo();
		bundle = getIntent().getExtras();
		coopVisitInfo = (CoopVisitInfoBean) bundle.getSerializable("coopVisitInfo");
		coopVisitSmallShopInfoList = (List<CoopVisitSmallShopInfoBean>) bundle
				.getSerializable("coopVisitSmallShopInfoList");
		option = new ArrayList<CoopVisitOptionInfoBean>();
		for (int i = 0; i < 6; i++) {
			if (i == 0) {
				option.add(new CoopVisitOptionInfoBean("", "请选择..."));
			} else {
				option.add(new CoopVisitOptionInfoBean("" + i, "" + i));
			}
		}
		spiAdapter = new ArrayAdapter<CoopVisitOptionInfoBean>(CoopVisitSmallShop.this,
				android.R.layout.simple_spinner_item, option);
		spiAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		optionChannle = new ArrayList<CoopVisitOptionInfoBean>();
		optionChannle.add(new CoopVisitOptionInfoBean("", "请选择..."));
		optionChannle.add(new CoopVisitOptionInfoBean("GHY", "GHY"));
		optionChannle.add(new CoopVisitOptionInfoBean("其他", "其他"));
		spiChannleAdapter = new ArrayAdapter<CoopVisitOptionInfoBean>(CoopVisitSmallShop.this,
				android.R.layout.simple_spinner_item, optionChannle);
		spiChannleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	}

	private void findView() {
		labTxtSmallShopId = (TextView) findViewById(R.id.labTxtSmallShopId);
		labTxtSmallShopName = (TextView) findViewById(R.id.labTxtSmallShopName);
		labTxtNotSalenum = (TextView) findViewById(R.id.labTxtNotSalenum);

		txtContent = (EditText) findViewById(R.id.txtContent);
		txtPernr = (EditText) findViewById(R.id.txtPernr);
		txtCustnum = (EditText) findViewById(R.id.txtCustnum);
		txtSalenum = (EditText) findViewById(R.id.txtSalenum);
		txtCustdisplay = (EditText) findViewById(R.id.txtCustdisplay);
		txtFirstcmptdisplay = (EditText) findViewById(R.id.txtFirstcmptdisplay);

		chkIssale = (CheckBox) findViewById(R.id.chkIssale);
		chkPjpvisit = (CheckBox) findViewById(R.id.chkPjpvisit);
		chkPrepare = (CheckBox) findViewById(R.id.chkPrepare);
		chkRegardcust = (CheckBox) findViewById(R.id.chkRegardcust);
		chkCleanshelf = (CheckBox) findViewById(R.id.chkCleanshelf);
		chkSdh = (CheckBox) findViewById(R.id.chkSdh);
		chkStock = (CheckBox) findViewById(R.id.chkStock);
		chkRecorder = (CheckBox) findViewById(R.id.chkRecorder);
		chkThisbuy = (CheckBox) findViewById(R.id.chkThisbuy);

		spiChannel = (Spinner) findViewById(R.id.spiChannel);
		spiChoosesku = (Spinner) findViewById(R.id.spiChoosesku);
		spiExpress = (Spinner) findViewById(R.id.spiExpress);
		spiPersu = (Spinner) findViewById(R.id.spiPersu);

		labTxtEntertime = (Button) findViewById(R.id.labTxtEntertime);
		labTxtLeavetime = (Button) findViewById(R.id.labTxtLeavetime);

		btnSubmit01 = (Button) findViewById(R.id.btnSubmit01);
		btnSubmit02 = (Button) findViewById(R.id.btnSubmit02);
		btnSubmit03 = (Button) findViewById(R.id.btnSubmit03);

	}

	private void init() {
		labTxtSmallShopId.setText(coopVisitInfo.getKunnr());
		labTxtSmallShopName.setText(coopVisitInfo.getKunnrname());

		spiChannel.setAdapter(spiChannleAdapter);
		spiChoosesku.setAdapter(spiAdapter);
		spiExpress.setAdapter(spiAdapter);
		spiPersu.setAdapter(spiAdapter);

		if (null != coopVisitSmallShopInfoList && coopVisitSmallShopInfoList.size() > 0) {
			coopVisitSmallShopInfo = coopVisitSmallShopInfoList.get(0);
			txtContent.setText(null == coopVisitSmallShopInfo.getContent() ? ""
					: coopVisitSmallShopInfo.getContent());
			labTxtEntertime.setText(null == coopVisitSmallShopInfo.getEntertime() ? ""
					: coopVisitSmallShopInfo.getEntertime().substring(11, 19));
			labTxtLeavetime.setText(null == coopVisitSmallShopInfo.getLeavetime() ? ""
					: coopVisitSmallShopInfo.getLeavetime().substring(11, 19));
			txtPernr.setText(null == coopVisitSmallShopInfo.getPernr() ? ""
					: coopVisitSmallShopInfo.getPernr());
			txtCustnum.setText(null == coopVisitSmallShopInfo.getCustnum() ? ""
					: coopVisitSmallShopInfo.getCustnum());
			txtSalenum.setText(null == coopVisitSmallShopInfo.getSalenum() ? ""
					: coopVisitSmallShopInfo.getSalenum());
			if (null != coopVisitSmallShopInfo.getCustnum()
					&& !"".equals(coopVisitSmallShopInfo.getCustnum())
					&& null != coopVisitSmallShopInfo.getSalenum()
					&& !"".equals(coopVisitSmallShopInfo.getSalenum())) {
				labTxtNotSalenum
						.setText((Integer.parseInt(coopVisitSmallShopInfo.getCustnum()) - Integer
								.parseInt(coopVisitSmallShopInfo.getSalenum())) + "");
			}
			if (null != coopVisitSmallShopInfo.getIssale()
					&& "是".equals(coopVisitSmallShopInfo.getIssale())) {
				chkIssale.setChecked(true);
			}
			if (null != coopVisitSmallShopInfo.getPjpvisit()
					&& "是".equals(coopVisitSmallShopInfo.getPjpvisit())) {
				chkPjpvisit.setChecked(true);
			}
			if (null != coopVisitSmallShopInfo.getPrepare()
					&& "是".equals(coopVisitSmallShopInfo.getPrepare())) {
				chkPrepare.setChecked(true);
			}
			txtCustdisplay.setText(null == coopVisitSmallShopInfo.getCustdisplay() ? ""
					: coopVisitSmallShopInfo.getCustdisplay());
			txtFirstcmptdisplay.setText(null == coopVisitSmallShopInfo.getFirstcmptdisplay() ? ""
					: coopVisitSmallShopInfo.getFirstcmptdisplay());
			if (null != coopVisitSmallShopInfo.getChannel()) {
				spiChannel.setSelection(
						getSpinnerSelectedItemPositionForChannle(coopVisitSmallShopInfo
								.getChannel()), true);
			}
			if (null != coopVisitSmallShopInfo.getRegardcust()
					&& "是".equals(coopVisitSmallShopInfo.getRegardcust())) {
				chkRegardcust.setChecked(true);
			}
			if (null != coopVisitSmallShopInfo.getCleanshelf()
					&& "是".equals(coopVisitSmallShopInfo.getCleanshelf())) {
				chkCleanshelf.setChecked(true);
			}
			if (null != coopVisitSmallShopInfo.getSdh()
					&& "是".equals(coopVisitSmallShopInfo.getSdh())) {
				chkSdh.setChecked(true);
			}
			if (null != coopVisitSmallShopInfo.getStock()
					&& "是".equals(coopVisitSmallShopInfo.getStock())) {
				chkStock.setChecked(true);
			}
			if (null != coopVisitSmallShopInfo.getRecorder()
					&& "是".equals(coopVisitSmallShopInfo.getRecorder())) {
				chkRecorder.setChecked(true);
			}
			if (null != coopVisitSmallShopInfo.getChoosesku()) {
				spiChoosesku
						.setSelection(getSpinnerSelectedItemPosition(coopVisitSmallShopInfo
								.getChoosesku()), true);
			}
			if (null != coopVisitSmallShopInfo.getExpress()) {
				spiExpress.setSelection(
						getSpinnerSelectedItemPosition(coopVisitSmallShopInfo.getExpress()), true);
			}
			if (null != coopVisitSmallShopInfo.getPersu()) {
				spiPersu.setSelection(
						getSpinnerSelectedItemPosition(coopVisitSmallShopInfo.getPersu()), true);
			}
			if (null != coopVisitSmallShopInfo.getThisbuy()
					&& "是".equals(coopVisitSmallShopInfo.getThisbuy())) {
				chkThisbuy.setChecked(true);
			}
		} else {
			coopVisitSmallShopInfo = new CoopVisitSmallShopInfoBean();
		}
	}

	private boolean getData() {
		if (null == coopVisitSmallShopInfo.getPartner()) {
			coopVisitSmallShopInfo.setPartner(labTxtSmallShopId.getText().toString().trim());
		}
		coopVisitSmallShopInfo.setVsdate(loginInfo.getNowdate().substring(0, 10));
		coopVisitSmallShopInfo.setCuser(loginInfo.getPernr());
		coopVisitSmallShopInfo.setContent(txtContent.getText().toString().trim());
		coopVisitSmallShopInfo.setPernr(txtPernr.getText().toString().trim());
		String custnumStr = txtCustnum.getText().toString().trim();
		String salenumStr = txtSalenum.getText().toString().trim();
		if (!"".equals(custnumStr) && !"".equals(salenumStr)) {
			int custnum = Integer.parseInt(custnumStr);
			int salenum = Integer.parseInt(salenumStr);
			int temp = custnum - salenum;
			if (temp < 0) {
				Toast.makeText(CoopVisitSmallShop.this, "已成交数必须小于网点数!", Toast.LENGTH_SHORT).show();
				return false;
			}
		}
		coopVisitSmallShopInfo.setCustnum(custnumStr);
		coopVisitSmallShopInfo.setSalenum(salenumStr);
		if (chkIssale.isChecked()) {
			coopVisitSmallShopInfo.setIssale("是");
		} else {
			coopVisitSmallShopInfo.setIssale("否");
		}
		if (chkPjpvisit.isChecked()) {
			coopVisitSmallShopInfo.setPjpvisit("是");
		} else {
			coopVisitSmallShopInfo.setPjpvisit("否");
		}
		if (chkPrepare.isChecked()) {
			coopVisitSmallShopInfo.setPrepare("是");
		} else {
			coopVisitSmallShopInfo.setPrepare("否");
		}
		coopVisitSmallShopInfo.setCustdisplay(txtCustdisplay.getText().toString().trim());
		coopVisitSmallShopInfo.setFirstcmptdisplay(txtFirstcmptdisplay.getText().toString().trim());
		if (chkRegardcust.isChecked()) {
			coopVisitSmallShopInfo.setRegardcust("是");
		} else {
			coopVisitSmallShopInfo.setRegardcust("否");
		}
		if (chkCleanshelf.isChecked()) {
			coopVisitSmallShopInfo.setCleanshelf("是");
		} else {
			coopVisitSmallShopInfo.setCleanshelf("否");
		}
		if (chkSdh.isChecked()) {
			coopVisitSmallShopInfo.setSdh("是");
		} else {
			coopVisitSmallShopInfo.setSdh("否");
		}
		if (chkStock.isChecked()) {
			coopVisitSmallShopInfo.setStock("是");
		} else {
			coopVisitSmallShopInfo.setStock("否");
		}
		if (chkRecorder.isChecked()) {
			coopVisitSmallShopInfo.setRecorder("是");
		} else {
			coopVisitSmallShopInfo.setRecorder("否");
		}
		if (chkThisbuy.isChecked()) {
			coopVisitSmallShopInfo.setThisbuy("是");
		} else {
			coopVisitSmallShopInfo.setThisbuy("否");
		}
		return true;
	}

	private void addListener() {

		spiChannel.setOnItemSelectedListener(new SpiListener("Channel"));
		spiChoosesku.setOnItemSelectedListener(new SpiListener("Choosesku"));
		spiExpress.setOnItemSelectedListener(new SpiListener("Express"));
		spiPersu.setOnItemSelectedListener(new SpiListener("Persu"));

		btnSubmit01.setOnClickListener(btnListener);
		btnSubmit02.setOnClickListener(btnListener);
		btnSubmit03.setOnClickListener(btnListener);

		txtCustnum.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				String custnumStr = ((EditText) v).getText().toString().trim();
				String salenumStr = txtSalenum.getText().toString().trim();
				if (!hasFocus && !"".equals(custnumStr) && !"".equals(salenumStr)) {
					int custnum = Integer.parseInt(custnumStr);
					int salenum = Integer.parseInt(salenumStr);
					int temp = custnum - salenum;
					if (temp >= 0) {
						labTxtNotSalenum.setText("  " + temp);
					} else {
						Toast.makeText(CoopVisitSmallShop.this, "已成交数必须小于网点数!", Toast.LENGTH_SHORT)
								.show();
					}
				}
			}
		});

		txtSalenum.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				String salenumStr = ((EditText) v).getText().toString().trim();
				String custnumStr = txtCustnum.getText().toString().trim();
				if (!hasFocus && !"".equals(custnumStr) && !"".equals(salenumStr)) {
					int custnum = Integer.parseInt(custnumStr);
					int salenum = Integer.parseInt(salenumStr);
					int temp = custnum - salenum;
					if (temp >= 0) {
						labTxtNotSalenum.setText("  " + temp);
					} else {
						Toast.makeText(CoopVisitSmallShop.this, "已成交数必须小于网点数!", Toast.LENGTH_SHORT)
								.show();
					}
				}
			}
		});
	}

	private class SpiListener implements OnItemSelectedListener {

		private String flag = "";

		public SpiListener(String flag) {
			this.flag = flag;
		}

		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			CoopVisitOptionInfoBean bean = (CoopVisitOptionInfoBean) parent
					.getItemAtPosition(position);
			if ("Channel".equals(flag)) {
				coopVisitSmallShopInfo.setChannel(bean.getOptionId());
			} else if ("Choosesku".equals(flag)) {
				coopVisitSmallShopInfo.setChoosesku(bean.getOptionId());
			} else if ("Express".equals(flag)) {
				coopVisitSmallShopInfo.setExpress(bean.getOptionId());
			} else if ("Persu".equals(flag)) {
				coopVisitSmallShopInfo.setPersu(bean.getOptionId());
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
		}
	}

	private View.OnClickListener btnListener = new View.OnClickListener() {

		@Override
		public void onClick(View paramView) {
			if (!getData()) {
				return;
			}
			httpThread = new HttpThread(handler);
			httpThread.doStart();
		}
	};

	private class HttpThread extends Thread {
		private Handler handle = null;

		public HttpThread(Handler hander) {
			handle = hander;
		}

		public void doStart() {
			progressDialog = new ProgressDialog(CoopVisitSmallShop.this);
			progressDialog.setTitle("提示信息");
			progressDialog.setMessage("正在请求数据，请稍等......");
			progressDialog.setCancelable(false);
			progressDialog.show();
			this.start();
		}

		public void run() {
			Message message = handle.obtainMessage();
			;
			bundle = new Bundle();
			String result = null;
			VsPartOpeService service = new VsPartOpeService();
			try {
				result = service.SendVsPartData(VSTYPE, coopVisitSmallShopInfo);
				progressDialog.dismiss();
				bundle.putString("result", result);
				message.what = CommonStatic.STATE_NORMAL;
			} catch (Exception ex) {
				progressDialog.dismiss();
				disposeException.handleException(ex);
			}
			message.setData(bundle);
			handle.sendMessage(message);
		}
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message m) {
			String result = m.getData().getString("result");
			switch (m.what) {
				case CommonStatic.STATE_NORMAL :
					if ("OK".equals(result)) {
						new AlertDialog.Builder(CoopVisitSmallShop.this).setTitle("提示信息")
								.setMessage("提交成功, 是否关闭此页面!")
								.setPositiveButton("确定", new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dlg, int sumthin) {
										CoopVisitSmallShop.this.finish();
									}
								}).setNeutralButton("取消", null).show();
					} else {
						new AlertDialog.Builder(CoopVisitSmallShop.this).setTitle("提示信息")
								.setMessage(result).setNeutralButton("关闭", null).show();
					}
					break;
			}
		}
	};

	private int getSpinnerSelectedItemPosition(String value) {
		int position = 0;
		for (int i = 0; i < option.size(); i++) {
			if (value.equals(option.get(i).getOptionId())) {
				position = i;
			}
		}
		return position;
	}

	private int getSpinnerSelectedItemPositionForChannle(String value) {
		int position = 0;
		for (int i = 0; i < optionChannle.size(); i++) {
			if (value.equals(optionChannle.get(i).getOptionId())) {
				position = i;
			}
		}
		return position;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			new AlertDialog.Builder(CoopVisitSmallShop.this).setTitle("提示信息").setMessage("确定退出?")
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dlg, int sumthin) {
							CoopVisitSmallShop.this.finish();
						}
					}).setNeutralButton("取消", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dlg, int sumthin) {
						}
					}).show();
		}
		return true;
	}
}
